import React from 'react';
import ReactDOM from 'react-dom';
import Modal from './Modal';

import './Dialog.less';

class Dialog extends React.Component {
    displayName = 'Dialog';

    static defaultProps = {
        visible: false,
        closeable: true,
        footer: true,
        okText: '确定',
        loading: false,
        cancleText: '取消'
    };

    componentDidMount () {
        this.layer = document.createElement('div');
        this.layer.className = 'cm-dialog-helper';
        document.body.appendChild(this.layer);

        const ele = document.querySelector('.cm-dialog-shadow');
        if (ele) {
            this.shadow = ele;
        } else {
            this.shadow = document.createElement('div');
            this.shadow.className = 'cm-dialog-shadow';
            document.body.appendChild(this.shadow);
        }

        this.renderLayer();
    }

    componentWillUnmount () {
        const el = this.layer;
        el.parentNode.removeChild(el);
    }

    componentDidUpdate () {
        this.renderLayer();
    }

    renderLayer () {
        if (this.layer) {
            const props = Object.assign({}, this.props);
            ReactDOM.render(<Modal {...props} ref={f => this.modal = f}/>, this.layer);
        }
        if (this.shadow) {
            const eles = document.querySelectorAll('.cm-dialog-helper');
            if (this.props.visible) {
                this.layer.classList.add('visible');
            } else {
                this.layer.classList.remove('visible');
            }
            let visible = false;
            if (eles.length) {
                eles.forEach(e => {
                    if (e.classList.contains('visible')) {
                        visible = true;
                    }
                });
            }
            this.shadow.style.display = visible ? 'block' : 'none';
        }
    }

    center () {
        this.modal.center();
    }

    render () {
        return null;
    }
}

export default Dialog;
